import 'package:flutter/widgets.dart';
import 'package:get/get.dart';

final kRouteObserver = RouteObserver<ModalRoute>();

abstract class GetxRouteAwareState<T extends StatefulWidget,
    S extends GetxController> extends State<T> with RouteAware {
  final String? tag = null;

  S get controller => Get.find<S>(tag: tag);

  /// 页面可见变更
  void onVisibleChange(bool value) {}

  @override
  @mustCallSuper
  void didChangeDependencies() {
    kRouteObserver.subscribe(this, ModalRoute.of(context)!);
    super.didChangeDependencies();
  }

  @override
  @mustCallSuper
  void dispose() {
    kRouteObserver.unsubscribe(this);
    super.dispose();
  }

  /// Called when the top route has been popped off, and the current route
  /// shows up.
  @override
  @mustCallSuper
  void didPopNext() {
    super.didPopNext();
    onVisibleChange(true);
  }

  /// Called when the current route has been pushed.
  @override
  @mustCallSuper
  void didPush() {
    super.didPush();
    onVisibleChange(true);
  }

  /// Called when the current route has been popped off.
  @override
  @mustCallSuper
  void didPop() {
    super.didPop();
    onVisibleChange(false);
  }

  /// Called when a new route has been pushed, and the current route is no
  /// longer visible.
  @override
  @mustCallSuper
  void didPushNext() {
    super.didPushNext();
    onVisibleChange(false);
  }
}
